<template>
    <div>
        <div style="margin-top: 52.5px;"></div>
        <div style="margin: 10px 0;">
            <el-button type="primary" @click="addCarousel">新增<i class="el-icon-circle-plus-outline"></i></el-button>
            <el-button type="danger" @click="batchDelete">批量删除<i class="el-icon-remove-outline"></i></el-button>
        </div>

        <el-table :data="tableData" border stripe :header-cell-class-name="headerBg" @selection-change="handleSelectionChange" v-loading="loading">
            <el-table-column
                type="selection"
                width="55">
            </el-table-column>
            <el-table-column prop="carouselId" label="轮播图ID">
            </el-table-column>
            <!-- slot-scope="scope"用于获取当前行数据对象 -->
            <el-table-column prop="carouselCover" label="图片" width="80">
                <template slot-scope="scope">
                    <el-image
                        style="width: 50px; height: 50px"
                        :src="scope.row.carouselCover"
                        fit="fill"
                        :preview-src-list="preview(scope.row)"
                        >
                        <!-- :preview-src-list="srcList" -->
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column prop="carouselSort" label="排序值" width="125" sortable>
            </el-table-column>
            <el-table-column prop="carouselHref" label="跳转地址">
            </el-table-column>
            <el-table-column prop="carouselCreateTime" label="添加时间" sortable>
            </el-table-column>
            <el-table-column prop="carouselUpdateTime" label="更新时间" sortable>
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template  slot-scope="scope">
                    <el-button type="success" @click="updateCarousel(scope.row)">编辑<i class="el-icon-edit"></i></el-button>
                    <!-- <el-popover
                        placement="top"
                        width="160"
                        v-model="visible">
                        <p>这是一段内容这是一段内容确定删除吗？</p>
                        <div style="text-align: right; margin: 0">
                            <el-button size="mini" type="text" @click="visible = false">取消</el-button>
                            <el-button type="primary" size="mini" @click="deleteCarousel(scope.row.carouselId)">确定</el-button>
                        </div>
                    </el-popover> -->
                    <el-button type="danger" @click="logicalDeleteCarousel(scope.row)">删除<i class="el-icon-remove-outline"></i></el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog class="updatedialog" :title=dialogTitle :visible.sync="dialogFormVisible" :center="true" width="35%">
            <el-form :model="form" ref="form" label-width="20%" class="demo-ruleForm">
                <el-form-item label="轮播图ID" prop="carouselId" v-show="idShow">
                    <el-input v-model="form.carouselId" readonly></el-input>
                </el-form-item>
                <el-form-item label="轮播图图片" prop="carouselCover">
                    <el-upload
                    ref="upload"
                    action="#"
                    :limit="1"
                    list-type="picture-card"
                    :on-change="handleFileChange"
                    :auto-upload="false">
                        <i slot="default" class="el-icon-plus"></i>
                        <div slot="file" slot-scope="{file}">
                            <img
                                class="el-upload-list__item-thumbnail"
                                :src="file.url" alt=""
                            >
                            <span class="el-upload-list__item-actions">
                                <span
                                class="el-upload-list__item-preview"
                                @click="handlePictureCardPreview(file)"
                                >
                                    <i class="el-icon-zoom-in"></i>
                                </span>
                                <span
                                v-if="!disabled"
                                class="el-upload-list__item-delete"
                                @click="handleRemove(file)"
                                >
                                    <i class="el-icon-delete"></i>
                                </span>
                            </span>
                        </div>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-form-item>
                <el-form-item label="排序值" prop="carouselSort">
                    <el-input v-model="form.carouselSort"></el-input>
                </el-form-item>
                <el-form-item label="跳转地址" prop="carouselHref">
                    <el-input v-model="form.carouselHref"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialogBtn">
                <el-button type="primary" @click="submit()">确 定</el-button>
                <el-button @click="resetForm('form')">重 置</el-button>
            </div>
        </el-dialog>
        <div style="padding: 10px 0;">
            <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageInfo.pageNow"
            :page-sizes="[2, 10, 15, 20]"
            :page-size="pageInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.totalCarousel">
            </el-pagination>
        </div>
    </div>
</template>

<script>
import axios from 'axios'

import { getCarouselList, addCarousel, logicalDeleteCarousel, logicalDeleteListCarousel} from '../../network/api/api-carousel.js'

export default {
    name: 'RecommendedProduct',
    data() {
        return {
            tableData: [
                // {
                //     carouselId: '1746483322634113025',
                //     carouselCreateTime: '2024-1-2 11:10:10',
                //     carouselUpdateTime: '2024-1-2 11:10:10',
                //     carouselSort: 1,
                //     carouselCover: 'https://yuetao-file.oss-cn-chengdu.aliyuncs.com/upload/img/yt1704329576995.jpg',
                //     carouselHref: 'www.baidu.com',
                //     srcList: [
                //         'https://yuetao-file.oss-cn-chengdu.aliyuncs.com/upload/img/yt1704329576995.jpg',
                //     ],
                // },
                // {
                //     carouselId: '17464831111111111111111',
                //     carouselCreateTime: '2024-1-2 11:10:10',
                //     carouselUpdateTime: '2024-1-2 11:10:10',
                //     carouselSort: 2,
                //     carouselCover: 'https://yuetao-file.oss-cn-chengdu.aliyuncs.com/upload/img/yt1704329313007.jpg',
                //     carouselHref: 'www.baidu.com',
                //     srcList: [
                //         'https://yuetao-file.oss-cn-chengdu.aliyuncs.com/upload/img/yt1704329576995.jpg',
                //     ],
                // },
                // {
                //     carouselId: '174648322222222222222',
                //     carouselCreateTime: '2024-1-2 11:10:10',
                //     carouselUpdateTime: '2024-1-2 11:10:10',
                //     carouselSort: 1,
                //     carouselCover: 'https://yuetao-file.oss-cn-chengdu.aliyuncs.com/upload/img/yt1703146097531.jpg',
                //     carouselHref: 'www.baidu.com',
                //     srcList: [
                //         'https://yuetao-file.oss-cn-chengdu.aliyuncs.com/upload/img/yt1704329576995.jpg',
                //     ],
                // },
            ],
            selectedTable: [],
            dialogFormVisible: false,
            dialogType: '',
            dialogTitle: '',
            picture: null, // 轮播图文件
            dialogImageUrl: '', // 修改弹框中轮播图url
            dialogVisible: false,
            disabled: false,
            visible: false,
            idShow: false,
            loading: true,
            form: {
                // carouselId: '',
                // carouselHref: '',
                // sarouselSort: -1,
                // carouselCover: '',
            },
            pageInfo: {
                pageNow: 1,     //当前页数
                pageSize: 10,   //每页显示的数据量
                totalCarousel: 0    //总数据量
            },
            headerBg: 'headerBg'
        }
    },
    mounted () {
        this.getCarouselList()
    },
    methods: {
        async getCarouselList(){
            try {
                this.loading = true
                const content = await getCarouselList(this.pageInfo.pageNow, this.pageInfo.pageSize)
                this.tableData = content.message.rows
                this.totalCarousel = content.message.total
            } catch (error) {
                this.$message.error(error)
            } finally {
                setTimeout(() => {
                    this.loading = false  // 请求完成后隐藏加载提示
                }, 1000); // 设置延迟时间为1秒钟
            }
        },
        // 点击表格中图片预览
        preview(row){
            var srcList = [];
            srcList[0] = row.carouselCover;
            return srcList
        },
        handleSizeChange(val) {
            //设置每页显示条数时，更新pageSize，重新获取图书列表
            this.pageInfo.pageSize = val
            this.getCarouselList()
        },
        handleCurrentChange(val) {
            //翻页或跳转特定页码时，更新当前页码pageNow，重新获取图书列表
            this.pageInfo.pageNow = val
            this.getCarouselList()
        },
        // 选中表格触发事件
        handleSelectionChange(val) {
            this.selectedTable = val
            console.log(this.selectedTable);
        },
        // 添加轮播图
        addCarousel() {
            this.idShow = false
            this.dialogFormVisible = true
            this.dialogType = 'add'
            this.dialogTitle = '添加轮播图'
            this.form = {} //清空弹框中的表单
        },
        // 批量删除
        async batchDelete() {
            if(this.selectedTable.length === 0){
                this.$message({
                    message: '请选择需要删除的推荐商品',
                    type: 'warning'
                });
            } else {
                try {
                    const content = await logicalDeleteListCarousel(this.selectedTable)
                    console.log(content);
                    this.getCarouselList()
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                } catch (error) {
                    this.$message(error)
                }
            }
        },
        // 修改轮播图
        updateCarousel(row){
            this.idShow = true
            this.dialogFormVisible = true
            this.form = JSON.parse(JSON.stringify(row))
            this.dialogType = 'update'
            this.dialogTitle = '修改轮播图'
        },
        // 删除轮播图(逻辑删除)
        async logicalDeleteCarousel(carousel) {
            try {
                // carousel.isDelete = 1
                const content = await logicalDeleteCarousel(carousel)
                if( content.message == 1 ) {
                    this.getCarouselList()
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                } else {
                    this.$message.error("删除失败")
                }
            } catch (error) {
                this.$message.error(error)
            }
            
        },
        // 弹框中的提交按钮
        submit(){
            var formData = new FormData();
            formData.append("file", this.picture);
            axios.post("/upload",formData,{
                headers:{
                    'Content-Type': 'multipart/form-data'
                }
            }).then(async (res) => {
                this.form.carouselCover = res.message[0];
                // 增加轮播图
                if(!this.idShow){
                    try {
                        // axios.defaults.headers.post['Content-Type'] = 'application/json'
                        const content = await addCarousel(this.form)
                        if(content.message === 1){
                            this.dialogFormVisible = false
                            this.getCarouselList()
                            this.$message({
                                message: '添加成功',
                                type: 'success'
                            });
                        } else {
                            this.$message.error("添加失败")
                        }
                    } catch (error) {
                        this.$message.error(error)
                    } finally {
                        this.handleRemove() // 移除弹框中的图片
                    }
                } else {
                    console.log("修改");
                }
            }).catch((error) => {
                this.$message.error(error)
            })
            
            
        },
        // 弹框中的重置按钮
        resetForm(formName) {
            this.$refs[formName].resetFields();
            // this.handleRemove();
        },
        // 上传图片时发生的事件
        handleFileChange(file, fileList) {
            // console.log(file);
            // console.log(fileList);
            if (fileList.length > 0) {
                this.picture = fileList[0].raw;
            } else {
                this.picture = null;
            }
        },
        // 移除上传的图片
        handleRemove(file) {
            console.log(file);
            this.$refs.upload.clearFiles(); // 清空上传列表
            this.picture = null; // 清除需要上传的图片文件
            this.dialogVisible = false; // 关闭预览弹窗
        },
        // 预览上传的图片
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
    }

}
</script>

<style scoped>
.headerBg {
    font-weight: 1000;
    color: black;
    background-color: #eee !important;
}

/* .demo-table-expand {
    font-size: 0;
}
.demo-table-item{
    margin-left: 100px;
}
.demo-table-expand label {
    font-weight: 1000;
    width: 90px;
    color: black;
}
.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    display: flex;
    flex-direction: row;
    align-items: center;
} */

.dialogBtn {
    text-align: center;
}

.demo-ruleForm .el-form-item{
    display: flex;
    align-items: center;
    /* justify-content: space-around; */
}

.demo-ruleForm {
    font-weight: 1000;
}

</style>